<template>
  <view>
    <!-- 播放视频弹出框 -->
    <mxp-popup ref="popupRef" model="bottom" :toolbarOptions="{ title: data.title }" height="580px" @confirm="hide">
      <video id="myVideo" :direction="0" showMuteBtn :poster="data.poster" class="video-full-screen" :src="data.videoUrl" @error="videoError"></video>
      <view class="save-video-button-box">
        <button class="save-video-button" :loading="data.saveLoading" :disabled="data.saveLoading" @click="saveVideoToPhotosAlbum()">
          <text class="save-video-button-text">保存视频</text>
        </button>
      </view>
    </mxp-popup>
    <mxp-toast ref="mxpToastRef"></mxp-toast>
  </view>
</template>

<script lang="ts" setup>
  import type { VideoOnErrorEvent } from 'mxp-uni-types';
  import MxpPopup from '../../mxp-popup/mxp-popup.vue';
  import MxpToast from '../../mxp-toast/mxp-toast.vue';

  import { getCurrentInstance, nextTick, onUnmounted, reactive, ref } from 'vue';
  defineOptions({
    name: 'mxp-video-preview-popup',
  });

  const popupRef = ref<InstanceType<typeof MxpPopup> | null>(null);
  const mxpToastRef = ref<InstanceType<typeof MxpToast> | null>(null);
  const instance = getCurrentInstance();
  const data = reactive({
    playVideoTimeout: undefined as NodeJS.Timeout | undefined,
    saveLoading: false,
    videoContext: undefined as UniApp.VideoContext | undefined, // 视频对象
    videoUrl: '', // 视频链接
    poster: '', // 缩略图
    title: '',
  });

  onUnmounted(() => {
    data.playVideoTimeout && clearTimeout(data.playVideoTimeout);
  });

  /** 显示 */
  function show(op: { url: string; poster?: string; title?: string }) {
    clearTimeout(data.playVideoTimeout);
    data.videoUrl = op.url;
    data.poster = op.poster || '';
    data.title = op.title || '视频预览';
    popupRef.value?.show({
      animationEnd(type: 'hide-animation' | 'show-animation') {
        if (type === 'show-animation') {
          nextTick(() => {
            data.videoContext = uni.createVideoContext('myVideo', instance); // this这个是实例对象 必传
            data.videoContext.play();
          });
        }
      },
    });
  }

  /** 关闭视频弹出框 */
  function hide() {
    clearTimeout(data.playVideoTimeout);
    data.videoContext?.pause();
    nextTick(() => {
      popupRef.value?.hide();
    });
  }

  /** 保存视频 */
  function saveVideoToPhotosAlbum() {
    // #ifndef H5
    data.saveLoading = true;
    uni.downloadFile({
      url: data.videoUrl,
      success: (res) => {
        // 2 成功下载后而且状态码为200时将视频保存到本地系统
        if (res.statusCode === 200) {
          uni.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success() {
              data.saveLoading = false;
              mxpToastRef.value?.showSuccess('保存成功');
            },
            fail(err1) {
              data.saveLoading = false;
              mxpToastRef.value?.showError('保存失败,—BD001');
              console.log('err========', err1);
            },
          });
        } else {
          data.saveLoading = false;
          mxpToastRef.value?.showError('下载视频失败—BD002');
        }
      },
      fail: (err) => {
        data.saveLoading = false;
        mxpToastRef.value?.showError('下载视频失败，—BD003');
        console.log('err========', err);
      },
    });
    // #endif

    // #ifdef H5
    mxpToastRef.value?.showWarning('H5端暂不支持保存');
    // #endif
  }
  /** 视频播放失败 */
  function videoError(err: VideoOnErrorEvent) {
    mxpToastRef.value?.showError('视频播放失败');
    console.log('err========', err);
  }

  defineExpose({
    /** 显示 */
    show,
    /** 隐藏 */
    hide,
  });
</script>

<style lang="scss" scoped>
  .global-popup-title-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 750rpx;
    height: 50px;
  }

  .global-popup-title {
    font-size: 16px;
    font-weight: bold;
  }

  .video-full-screen {
    width: 690rpx;
    height: 200px;
    margin-top: 50px;
    margin-left: 30rpx;
    overflow: hidden;
    border-radius: 6px;
  }

  .save-video-button-box {
    width: 690rpx;
    margin-top: 50px;
    margin-left: 30rpx;
  }

  .save-video-button {
    background: #4b6bf6;

    &:after {
      border: none;
    }
  }

  .save-video-button-text {
    font-size: 18px;
    color: #ffffff;
  }
</style>
